/*
选择角色
*/

layui.define(['form', 'cosjs','scene'], function (exports) {
    let $ = layui.jquery,form = layui.form,scene = layui.scene;

    function select() {
        let data = {};
        data.roles = scene.gamesdk.game.roles;
        return data;
    }

    select.finish = function () {
        form.on('submit(game-create-show)', function () {
            scene.show('game/create');
            return false;
        })

        form.on('submit(game-select-submit)', function (fd) {
            let data = fd.field
            let uid = data['uid'];
            select.submit(uid);
            return false;
        })
    }


    select.submit = function submit(uid){
        let modules = scene.gamesdk.game.modules;
        let maxmod = Object.keys(modules).length;
        if(!maxmod){
            return scene.show('game/main');
        }

        let _curUser=layui.storage('curUser');
        _curUser.set('gameSelectData',uid);


        return scene.gamesdk.game.select(uid).then(() => {
            return scene.show('progress',maxmod);
        }).then((progress)=>{
            //预加载游戏模块
            let task = scene.gamesdk.game.initialize();
            task.interval = 1000;
            task.on("begin", (k) => {
                let opt = modules[k];
                $('#progress-title').html(`${opt.name}`)
                console.log(`game initialize ${opt.name} begin`);
            })
            task.on("result", (k, err, ret) => {
                progress.add(1);
                let opt = modules[k];
                console.log(`game initialize ${opt.name} finish`, err, ret);
            })
            return task.start();
        }).then(() => {
            scene.show('game/main');
        }).catch(err => {
            return cosjs.error(err);
        })
    }

    exports('game/select', select);
})